<template>
  <el-dialog
    :title="addForm.id > 0 ? '编辑用户分组' : '添加用户分组'"
    v-model="dialogVisble"
    width="35%"
    :before-close="closeBox"
  >
    <div>
      <el-form
        ref="formRef"
        style="max-width: 500px"
        :model="addForm"
        :rules="roleRules"
        label-width="auto"
        class="demo-dynamic"
      >
       
        <el-form-item prop="name" label="名称">
          <el-input v-model="addForm.name" />
        </el-form-item>

        <el-form-item label="说明" prop="des">
          <el-input v-model="addForm.des" type="textarea" />
        </el-form-item>

        <el-form-item label="状态" prop="state" v-if="addForm.id > 0">
          <el-switch v-model="addForm.state" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeBox">取 消</el-button>
        <el-button type="primary" @click="submitForm(formRef)">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, computed, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";

const pors = defineProps({
  showdialog: {
    type: Boolean,
    default: false,
  },
  list: {
    type: Object,
    default: {
      id: 0,
      name: "", //名称
      des: "", // 说明
      state: "", //状态
    },
  },
});
const formRef = ref<FormInstance>(); //定义form
//表单提交元素
const addForm = computed(() => pors.list);
// const addForm = reactive({});
//表单元素的规则
const roleRules = reactive({
  name: [
    {
      required: true,
      message: "请输入名称",
      trigger: "blur", //验证逻辑的触发方式
    },
  ],
});

const emits = defineEmits(["useConfirm", "useClose"]); //定义一个或多个自定义按钮事件 传递到父组件

const dialogVisble = ref(false); // 定义控制弹窗显隐的变量

//关闭模态框
const closeBox = () => {
  if (!formRef) return;
  formRef.value.resetFields();
  dialogVisble.value = false; //重置为空
  emits("useClose", dialogVisble.value);
};

//确定/提交
const submitForm = (formData: FormInstance | undefined) => {
  if (!formData) return;
  //校验
  formData.validate((valid) => {
    if (valid) {
      // console.log();

      dialogVisble.value = false;
      emits("useConfirm", addForm.value);
      formData.resetFields(); //重置为空
    } else {
      console.log("error submit!");
      return false;
    }
  });
};

// 将变量暴露出来
defineExpose({
  dialogVisble,
});
</script>
